package controller;

import java.io.BufferedReader;
import java.io.File;
import java.io.FileNotFoundException;
import java.io.FileReader;
import java.io.IOException;
import java.net.InetAddress;
import java.net.UnknownHostException;
import javax.swing.JFrame;

import model.Mode;

public class Parser {

	private Controller controller;

	Parser(Controller controller){
		this.controller = controller;
	}
	public void parseFiles(File[] files, JFrame frame, Mode mode){
		for (File file: files){
			checkFile(file, frame, mode);
		}
	}
	private void checkFile(File file, JFrame frame, Mode mode){
		if (file.isFile() && file.canRead()){
			parseFile(file, mode);
		}
	}
	private void parseFile(File file, Mode mode){
		BufferedReader in;
		try {
			in = new BufferedReader(new FileReader(file));
			String line = in.readLine();
			while (line!=null){
				processLine(line, mode);
				line = in.readLine();
			}
			in.close();
		} catch (FileNotFoundException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		} catch (IOException e) {
			// TODO Auto-generated catch block
			e.printStackTrace();
		}

	}
	private void processLine(String line, Mode mode){
		String trimmed = line.trim();
		if(trimmed.length()>0){
			try {
				//throws an unknownhost exception
				InetAddress address = InetAddress.getByName(line);
				
				//only occurs if exception not thrown
				String hostname = address.getHostName();
				if(address.getHostAddress().equals(hostname)){
					//could not resolve
					controller.addUnknownHost(line);
				}
				else{
					//could resolve
					
					//hostname mode
					if(mode == Mode.HOSTNAME){
						controller.addKnownHost(hostname);	
					}
					//IP address mode
					else{
						controller.addKnownHost(address.getHostAddress());	
					}
					
				}
				
				
			} catch (UnknownHostException e) {
				controller.addUnknownHost(line);
			}
		}
	}

}
